package com.lancoo.cvas.util;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lancoo.cvas.pojo.common.PageInfo;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName PagingUtil
 * @Description 分页相关
 * @Author quin
 * @Date 2023/1/13 15:05
 */
public class PagingUtil {

    /**
     * 对list进行分页
     *
     * @param currentPage
     * @param pageSize
     * @param list
     * @return
     */
    public static <T> PageInfo<T> getPages(Integer currentPage, Integer pageSize, List<T> list) {
//        Page page = new Page();
        PageInfo<T> page = new PageInfo<T>();
        int size = list.size();

        if (pageSize > size) {
            pageSize = size;
        }

        if (pageSize == 0) {
            page.setCurrentPage(currentPage).
                    setPageSize(pageSize).
                    setTotal(list.size()).
                    setList(list);
            return page;
        }

        //求出最大页数，防止currentPage越界
        int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;

        if (currentPage > maxPage) {
            currentPage = maxPage;
        }

        //计算 当前页第一条数据下标
        int curIds = currentPage > 1 ? (currentPage - 1) * pageSize : 0;

        List<T> pageList = new ArrayList<>();

        //将当前页的数据放进pageList
        for (int i = 0; i < pageSize && curIds + i < size; i++) {
            pageList.add(list.get(curIds + i));
        }

        //向page对象中手动设置各项分页的参数
        page.setCurrentPage(currentPage).
                setPageSize(pageSize).
                setTotal(list.size()).
                setList(pageList);
        //计算分页总页数
        page.setPages(size % pageSize == 0 ? size / pageSize : size / pageSize + 1);

        return page;

    }

    /**
     * 将mybatisplus分页对象封装
     *
     * @param iPage
     * @return
     */
    public static <T> PageInfo<T> formatPageResult(IPage<T> iPage) {
        PageInfo<T> pageInfo = new PageInfo<>();
        pageInfo.setCurrentPage(iPage.getCurrent())
                .setPageSize(iPage.getSize())
                .setTotal(iPage.getTotal())
                .setPages(iPage.getPages())
                .setList(iPage.getRecords());
        return pageInfo;
    }

}
